using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

using System.Diagnostics;
using System.Net.Http;

using Web.Mvc.Models;
using Web.MVC.Helper;

namespace Web.Mvc.Controllers
{
   
    public class HomeController : Controller
    {
       
        private readonly IHttpClientFactory _httpClientFactory;
     

        private readonly ILogger<HomeController> _logger;
        private readonly IServiceHelper _serviceHelper;

        public HomeController(ILogger<HomeController> logger, IServiceHelper serviceHelper,IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _serviceHelper = serviceHelper;
            _httpClientFactory = httpClientFactory;
        }

        public async Task<IActionResult> Index()
        {
        
          

            return View();
        }
        [Authorize]
        public async Task<IActionResult> Privacy()
        {
            var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
            //var client = _httpClientFactory.CreateClient();
            //var gateway = "https://localhost:7236";
            //var downStreamUrl = "/product/GetProductList";
            //client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
            //try
            //{
            //    var res = await client.GetStringAsync(gateway + downStreamUrl);
            //    return Ok(res);
            //}
            //catch (Exception ex)
            //{
            //    var myex = ex;
            //}
            //return BadRequest("数据错误");
            Console.WriteLine("认证成功，执行后台api获取");
            ViewBag.OrderData = await _serviceHelper.GetOrder(accessToken);
            ViewBag.ProductData = await _serviceHelper.GetProduct(accessToken);
            ViewBag.Token = accessToken;
            // _serviceHelper.GetServices();
            // ViewBag.OrderData = await _serviceHelper.GetOrder(accessToken);
            //    ViewBag.ProductData = await _serviceHelper.GetProduct(accessToken);
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
